<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    body {
      height: 2000px;
      background: linear-gradient(red, green, blue);
    }

    button {
      position: fixed;
      bottom: 40px;
      right: 30px;
      display: none;
    }
  </style>
</head>

<body>
  <button id="btn">回到顶部</button>
  <script>
    // onscroll 元素或整个窗口的滚动事件
    var btn = document.getElementById("btn");
    window.onscroll = function () {

      // 当页面滚动距离大于500显示回到顶部按钮 否则 不显示
      var mybody = document.documentElement || document.body;
      var top = mybody.scrollTop;
      if (top > 500) {
        btn.style.display = "block"
      } else {
        btn.style.display = "none"
      }
    }
    // 点击回到顶部
    btn.onclick = function () {
      var mybody = document.documentElement || document.body;
      mybody.scrollTop = 0;
    }

  </script>
</body>

</html>